import axios from 'axios'
import Env from 'react-native-config'
import Storge from  '@/utils/storge'

function request(requestMethod, url, data) {

  // 获取本地token
  let token = Storge.getValue('token')
  console.log('token', token)
  // 配置请求头
  const config = {
    headers: {}, // 请求头
    timeout: 5000
  }

  if (token) config.headers['token'] = token

  config.method = requestMethod // 请求方式

  // 根据请求方式的传参key值进行变化
  if (requestMethod === 'get' && data) {
    config.params = data
  } else if (requestMethod === 'post') {
    config.data = data
  }

  config.url = Env.API_URL + url // url = base url + request url

  console.log(' config.url',  config.url);
  return new Promise((resolve, reject) => {
    axios(config)
      .then(res => {
        if (res.data.errorCode === 0) {
          resolve(res.data.result)
          // if (res.headers) {
          //   res.data.headers = res.headers
          // }
        } else {
          reject(res.data)
          // return handleScene(reject, res.data.errorCode, res.data.errorMsg)
        }
      })
      .catch(err => {
        reject(err)
        // return handleScene(reject, -1, '网络出错')
      })
  })
}

/**
 * 处理各类场景错误
 * @param {*} reject promise中reject参数
 * @param {*} code 错误码
 * @param {*} msg 错误信息
 */

// function handleScene(reject, code, msg) {}

// get请求封装
function get(url, params) {
  return request('get', url, params)
}
// post请求封装
function post(url, postData) {
  return request('post', url, postData)
}
// put请求封装
function put(url, putData) {
  return request('put', url, putData)
}
export default ({
  post,
  get,
  put
})

